package com.fancyy.scm.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ObservableBoolean;
import android.databinding.ViewDataBinding;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.fancyy.scm.BRActivityManager;
import com.fancyy.scm.BRApplication;
import com.fancyy.scm.R;
import com.fancyy.scm.base.annotation.Layout;
import com.fancyy.scm.base.annotation.Translucent;
import com.fancyy.scm.bean.UserInfo;
import com.fancyy.scm.util.StatusBarUtil;
import com.fancyy.scm.util.ToastUtil;

import java.lang.reflect.Field;

/**
 * 所有Activity页面的抽象父类
 *
 * @param <DataBinding> 数据绑定者
 */
public abstract class BaseFragmentActivity<DataBinding extends ViewDataBinding> extends FragmentActivity {

    public ObservableBoolean isRefreshing = new ObservableBoolean(false);

    public SwipeRefreshLayout.OnRefreshListener onRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            doOnRefresh();
        }
    };

    public void doOnRefresh() {

    }

    public void doLoadMore() {

    }

    private DataBinding dataBinding;

    private boolean onCreateInvoke = false;

    private boolean autoChangeStatusBar = true;

    public void setAutoChangeStatusBar(boolean autoChangeStatusBar) {
        this.autoChangeStatusBar = autoChangeStatusBar;
    }

    /**
     * 绑定一个布局(请在onCreate()方法之前调用)
     * 使用Layout注解将覆盖此方法
     *
     * @param layoutResID
     * @param title
     * @param rightButtonText
     */
    public void bindLayout(int layoutResID, String title, String rightButtonText) {
        bindLayout(layoutResID, title, rightButtonText, -1);
    }

    /**
     * 绑定一个布局(请在onCreate()方法之前调用)
     * 使用Layout注解将覆盖此方法
     *
     * @param layoutResID
     * @param title
     * @param rightButtonResId
     */
    public void bindLayout(int layoutResID, String title,
                           String rightButtonText, int rightButtonResId) {
        if (onCreateInvoke == true) {
            throw new RuntimeException("bindLayout方法必须在onCreate方法之前调用");
        }
        dataBinding = DataBindingUtil.setContentView(this, layoutResID);
//        TextView titleView = (TextView) findViewById(R.id.actionbarTitle);
//        if (titleView != null) {
//            titleView.setText(title);
//        }
//        ImageView rightButtonImageView = (ImageView) findViewById(R.id.imageButton);
//        if (rightButtonImageView != null && rightButtonResId > 0) {
//            rightButtonImageView.setImageResource(rightButtonResId);
//            rightButtonImageView.setOnClickListener(v -> onRightButtonClick());
//        }
//        TextView rightButtonTextView = (TextView) findViewById(R.id.textButton);
//        if (rightButtonTextView != null && !TextUtils.isEmpty(rightButtonText)) {
//            rightButtonTextView.setText(rightButtonText);
//            rightButtonTextView.setOnClickListener(v -> onRightButtonClick());
//        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        BRActivityManager.addActivity(this);
        super.onCreate(savedInstanceState);

        // 布局注入
        Layout layout = getClass().getAnnotation(Layout.class);
        if (layout != null) {
            bindLayout(layout.value(), layout.title(),
                    layout.rightButton(), layout.rightButtonRes());
        }
        onCreateInvoke = true;

        // 绑定activity对象到布局
        bindViewModelToUI();

        // 透明状态栏
        handleStatusBar();
    }

    protected void handleStatusBar() {
        Translucent translucentAnnotation = getClass().getAnnotation(Translucent.class);
        if (translucentAnnotation != null && translucentAnnotation.value()) {
            StatusBarUtil.setTranslucent(this);
        } else {
            // 非透明状态栏采用黑色风格 + 白色statusBar
            if (autoChangeStatusBar) {
                StatusBarUtil.setTranslucent(this);
                StatusBarUtil.setColorWithColorIntValue(this, Color.TRANSPARENT);
                boolean support = StatusBarUtil.setDarkStyleTitleBar(this);
                View rootView = ((getWindow().getDecorView().findViewById(android.R.id.content)));
                rootView.setPadding(0, StatusBarUtil.getStatusBarHeight(this), 0, 0);
//                if (support) {
//                    rootView.setBackgroundColor(getResources().getColor(R.color.nhs_bg_white));
//                } else {
//                    rootView.setBackgroundColor(getResources().getColor(R.color.nhs_bg_gray2));
//                }
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BRActivityManager.removeActivity(this);
    }

    /**
     * 获取数据绑定对象
     *
     * @return
     */
    public DataBinding getDataBinding() {
        return dataBinding;
    }

    /**
     * 打开一个页面
     *
     * @param activityClass
     */
    public void startActivity(Class<? extends Activity> activityClass) {
        startActivity(activityClass, false);
    }

    /**
     * 打开一个页面
     * 并且设置成是否关闭当前页面
     *
     * @param activityClass
     * @param finishSelf
     */
    public void startActivity(Class<? extends Activity> activityClass, boolean finishSelf) {
        Intent intent = new Intent(this, activityClass);
        startActivity(intent);
        if (finishSelf) {
            finish();
        }
    }

    /**
     * 使得XML布局文件中可以用viewModel
     */
    private void bindViewModelToUI() {
        if (dataBinding != null) {
            // 绑定两者
            Field[] declaredFields = dataBinding.getClass().getDeclaredFields();
            for (Field declaredField : declaredFields) {
                if (declaredField.getType().equals(getClass())) {
                    declaredField.setAccessible(true);
                    try {
                        declaredField.set(dataBinding, this);
                    } catch (IllegalAccessException e) {
                    }
                    declaredField.setAccessible(false);
                    break;
                }
            }
        }
    }

    /**
     * 获取当前登录用户
     *
     * @return
     */
    public UserInfo getLoginUser() {
        return getBRApplication().getUserInfo();
    }

    /**
     * 返回控件被点击
     *
     * @param view
     */
    public void onBackButtonClick(View view) {
        finish();
    }

    /**
     * 标题栏右上角按钮
     * 子类需要重写此方法来获取该按钮被点击时的监听
     */
    public void onRightButtonClick() {

    }

    /**
     * 返回当前对象本身,简化 XXXActivity.this
     *
     * @return
     */
    public Activity self() {
        return this;
    }

    /**
     * 获取当前应用程序的全局变量
     *
     * @return
     */
    public BRApplication getBRApplication() {
        return (BRApplication) getApplication();
    }

    /**
     * 弹出一个提示信息框
     *
     * @param message
     */
    public void showToast(String message) {
        ToastUtil.showToast(this, message);
    }


    /**
     * 自动隐藏软键盘
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}
